package com.ruoyi.common.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@ConfigurationProperties(prefix = "personposition")
public class PersonPosition {

    private static String http;

    private static String clientId;

    private static String grantType;

    private static String clientSecret;

    private static String getToken;

    private static String checkToken;

    private static String token;

    private static String countTotal;

    public static String getCountTotal() {
        return countTotal;
    }

    public static void setCountTotal(String countTotal) {
        PersonPosition.countTotal = countTotal;
    }

    public String getHttp() {
        return http;
    }

    public void setHttp(String http) {
        this.http = http;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getGrantType() {
        return grantType;
    }

    public void setGrantType(String grantType) {
        this.grantType = grantType;
    }

    public String getClientSecret() {
        return clientSecret;
    }

    public void setClientSecret(String clientSecret) {
        this.clientSecret = clientSecret;
    }

    public String getGetToken() {
        return getToken;
    }

    public void setGetToken(String getToken) {
        this.getToken = getToken;
    }

    public String getCheckToken() {
        return checkToken;
    }

    public void setCheckToken(String checkToken) {
        this.checkToken = checkToken;
    }

    public static String getToken() {
        if (token != null) {
            Boolean aBoolean = checkToken();
            if (aBoolean) {
                return token;
            }
        }
        String url = http + getToken;
        HttpResponse execute = HttpRequest
                .get(url)
                .form("client_id", clientId, "grant_type", grantType, "client_secret", clientSecret)
                .timeout(5000).execute();
        int status = execute.getStatus();
        if (status != 200) {
            return null;
        } else {
            String body = execute.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String access_token = jsonObject.getStr("access_token");
            if (StrUtil.isNotEmpty(access_token)) {
                token = access_token;
                return token;
            }
        }
        return null;
    }

    public static Boolean checkToken() {
        String url = http + checkToken;
        if (StrUtil.isEmpty(token)) {
            return false;
        } else {
            HttpResponse httpResponse = HttpRequest
                    .get(url)
                    .timeout(3000)
                    .form("token", PersonPosition.token)
                    .execute();
            int status = httpResponse.getStatus();
            if (status != 200) {
                return false;
            } else {
                String body = httpResponse.body();
                JSONObject jsonObject = JSONUtil.parseObj(body);
                Boolean active = jsonObject.getBool("active");
                return active;
            }
        }
    }


    public static JSONArray findHistory(JSONObject param) {
        String url = http + "/positionApi/api/record/findHistory?access_token=" + PersonPosition.getToken();

        HttpResponse httpResponse = HttpRequest
                .post(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .timeout(3000)
                .body(JSONUtil.toJsonStr(param))
                .execute();
        log.info("人员历史轨迹：{}", httpResponse.toString());

        int status = httpResponse.getStatus();
        if (status != 200) {
            return null;
        } else {
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONArray records = jsonObject.getJSONArray("data");
            return records;
        }

    }

    /**
     * 查询所有人员信息
     * @return
     */
    public static JSONObject dataList() {
        String url = http + "/positionApi/api/staff/dataList?access_token=" + PersonPosition.getToken();

        JSONObject param = new JSONObject();
        param.set("type", 1);
        param.set("orgId", 100);
        param.set("pageNum", 1);
        param.set("pageSize", 1000);

        HttpResponse httpResponse = HttpRequest
                .post(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .timeout(3000)
                .body(JSONUtil.toJsonStr(param))
                //.form("type", 1)
                .execute();
        log.info("人员历史轨迹：{}", httpResponse.toString());

        int status = httpResponse.getStatus();
        if (status != 200) {
            return null;
        } else {
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            return jsonObject;
        }
    }

    /**
     * 根据围栏ID获取详情
     * @return
     */
    public static JSONObject enclosure(String id) {
        String url = http + "/positionApi/api/warnTrigger/getEnclosureById/"+id+"?access_token=" + PersonPosition.getToken();

        HttpResponse httpResponse = HttpRequest
                .get(url)
                .timeout(3000)
                //.form("type", 1)
                .execute();
        log.info("围栏详情：{}", httpResponse.toString());
        int status = httpResponse.getStatus();
        if (status != 200) {
            return null;
        } else {
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONObject data = jsonObject.getJSONObject("data");
            return data;
        }
    }

    /**
     * 根据用户ID获取详情
     * @return
     */
    public static JSONObject user(Integer userId) {
        String url = http + "/positionApi/api/staff/dataList?access_token=" + PersonPosition.getToken();

        JSONObject param = new JSONObject();
        param.set("type", 1);
        param.set("orgId", 100);
        HttpResponse httpResponse = HttpRequest
                .post(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .timeout(3000)
                .body(JSONUtil.toJsonStr(param))
                //.form("type", 1)
                .execute();
        log.info("用户详情：{}", httpResponse.toString());
        int status = httpResponse.getStatus();
        if (status != 200) {
            return null;
        } else {
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray records = data.getJSONArray("records");
            for (Object record : records) {
                JSONObject re = new JSONObject(record);
                Integer id = re.getInt("id");
                if (id.equals(userId)) {
                    return re;
                }
            }
            return null;
        }
    }

    public static String login() {

        String url = http + "/position/login";

        JSONObject param = new JSONObject();
//        param.set("username", "manager");
        param.set("username", "GUEST");
        param.set("password", "123456");
        param.set("tenantId", "sc22120928");

        HttpResponse httpResponse = HttpRequest
                .post(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .timeout(3000)
                .body(JSONUtil.toJsonStr(param))
                .execute();
        log.info("获取登录token {}", httpResponse.toString());
        int status = httpResponse.getStatus();
        if (status != 200) {
            return null;
        } else {
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String token = jsonObject.getStr("token");
            return token;
        }
    }

    public static Object count() {

        String url = http + "/positionApi/api/statistics/getPositionCount?access_token=" + PersonPosition.getToken();

        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("orgId", "100");

        HttpRequest request = HttpRequest
                .post(url)
                .charset("UTF-8")
                .body(JSONUtil.toJsonPrettyStr(requestMap))
                .contentType("application/json")
                .timeout(3000);

        log.info("获取登录实时总数统计，请求体 {}", request.toString());
        HttpResponse httpResponse = request.execute();
        log.info("获取登录实时总数统计，响应体 {}", httpResponse.toString());

        int status = httpResponse.getStatus();
        if (status != 200) {
            return null;
        } else {
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            return jsonObject;
        }
    }



//    public static Map<String, Object> sendRequestForJsonData(String url, Map<String, Object> requestMap, Method method) {
//        HttpRequest httpRequest = new HttpRequest(url)
//                .header(Header.CONTENT_TYPE, "application/json; charset=UTF-8")
//                .header(Header.ACCEPT, "application/json")
//                .header(Header.ACCEPT_ENCODING, "");
//
//        httpRequest.method(method);
//        httpRequest.body(new JSONObject(requestMap).toString());
//
//        // 执行请求
//        HttpResponse response = httpRequest.execute();
//        Map map = new HashMap<String, Object>();
//        try {
//            String body = response.body();
//            map = new ObjectMapper().readValue(body, Map.class);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return map;
//    }
}
